// MySQLManager.hpp
#pragma once

#include <mariadb/mysql.h>
#include <string>
#include <vector>
#include <iostream>

class MySQLManager {
private:
    MYSQL *conn;
    std::string errorMessage;

public:
    MySQLManager() : conn(nullptr) {}

    ~MySQLManager() {
        closeDatabase();
    }

    bool openDatabase(const std::string &host, const std::string &user, const std::string &password, const std::string &dbname) {
        conn = mysql_init(nullptr);
        if (!conn) {
            errorMessage = "MySQL initialization failed";
            return false;
        }
        
        if (!mysql_real_connect(conn, host.c_str(), user.c_str(), password.c_str(), dbname.c_str(), 0, nullptr, 0)) {
            errorMessage = mysql_error(conn);
            return false;
        }
        return true;
    }

    void closeDatabase() {
        if (conn) {
            mysql_close(conn);
            conn = nullptr;
        }
    }

    std::string getErrorMessage() const {
        return errorMessage;
    }

    bool executeQuery(const std::string &query) {
        if (mysql_query(conn, query.c_str())) {
            errorMessage = mysql_error(conn);
            return false;
        }
        return true;
    }

    std::vector<std::vector<std::string>> executeSelect(const std::string &query) {
        std::vector<std::vector<std::string>> results;
        if (mysql_query(conn, query.c_str())) {
            errorMessage = mysql_error(conn);
            return results;
        }

        MYSQL_RES *res = mysql_store_result(conn);
        if (!res) {
            errorMessage = mysql_error(conn);
            return results;
        }

        MYSQL_ROW row;
        while ((row = mysql_fetch_row(res))) {
            std::vector<std::string> rowData;
            for (unsigned int i = 0; i < mysql_num_fields(res); ++i) {
                rowData.push_back(row[i] ? row[i] : "NULL");
            }
            results.push_back(rowData);
        }
        mysql_free_result(res);
        return results;
    }
};
